package ua.pp.shell.wka;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;

class App {
	public enum activities {
	    VOCABULARY_LIST,
	    AE_VOCABULARY,
	    WORD_LIST,
	    AE_WORD,
	    TEACH
	}
}

public class Settings {
	private final String APPLICATION = "ua.pp.shell";
	SharedPreferences shared = null;

	public void SetCurrentVocabulary(int current_vocabulary_id) {
		SharedPreferences.Editor editor = shared.edit();
	    editor.putInt("current_vocabulary_id", current_vocabulary_id);
	    editor.commit();
	}
	
	public void Copy(File from_file, File to_file) {
		try {
	            //if (from_file.exists()) {
	            	Log.v("S5", "File to copy exists");
	            	Log.v("S5", from_file.toString());
	            	Log.v("S5", Boolean.toString(from_file.exists()));
	            	Log.v("S5", to_file.toString());
	            	Log.v("S5", Boolean.toString(to_file.exists()));
	                FileChannel from_channel = new FileInputStream(from_file).getChannel();
	                FileChannel to_channel = new FileOutputStream(to_file).getChannel();
	                to_channel.transferFrom(from_channel, 0, from_channel.size());
	                from_channel.close();
	                to_channel.close();
	            //} else {
	            	Log.v("S5", "File to copy does not exist.");
	            //}
	    } catch (Exception e) {
	    	Log.v("S5", "Uncaughed error in Copy function");
	    }
	}
	
	public void SaveToSD() {
		try {
			File sd = Environment.getExternalStorageDirectory();
		    File directory = Environment.getDataDirectory();
	        if (sd.canWrite()) {
	        	String currentDBPath = "data/ua.pp.shell.wka/databases/wka";
		        String backupDBPath = "wka";
		        File currentDB = new File(directory, currentDBPath);
		        File backupDB = new File(sd, backupDBPath);
		        Copy(currentDB, backupDB);
	        }
	    } catch (Exception e) {
	    }
	}
	
	public void LoadFromSD() {
		try {
			Log.v("S5", "Hi from load from sd.");
			File sd = Environment.getExternalStorageDirectory();
		    File directory = Environment.getDataDirectory();
	        if (sd.canWrite()) {
	        	Log.v("S5", "SD is writeable");
	        	String currentDBPath = "/data/ua.pp.shell.wka/databases/wka";
		        String backupDBPath = "wka";
		        File currentDB = new File(directory, currentDBPath);
		        File backupDB = new File(sd, backupDBPath);
		        Copy(backupDB, currentDB);
	        }
	    } catch (Exception e) {
	    	Log.v("S5", "Uncaughted error.");
	    }
	}
	
	public int GetCurrentVocabulary() {
		return shared.getInt("current_vocabulary_id", -1);
	}
	
	public Settings(Context context) {
		shared = context.getSharedPreferences(APPLICATION, 0);
	}
}
